package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.UserService;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login.ctl")
public class LoginCtrl extends HttpServlet {
    /* JSON请求体 */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String user_json = JSONUtil.getJSON(request);
        //将JSON字串解析为User对象
        User userToLogin = JSON.parseObject(user_json, User.class);

        //创建JSON对象message, 以便往前端响应信息
        JSONObject message = new JSONObject();

        try {
            ServiceFactory.getService(UserService.class, "UserServiceImpl").login(userToLogin);
            if (userToLogin.getId() == null) {
                message.put("msg", "用户不存在/密码错误");
                message.put("code", "500");
                response.getWriter().println(JSON.toJSONString(message));
            } else {
                //构建响应信息
                message.put("msg", "操作成功");
                message.put("code", "200");
                //响应正常数据
                response.getWriter().println(JSON.toJSONString(message));
            }
        } catch (SQLException e) {
            message.put("msg", "数据库操作异常");
            //响应message到前端
            response.getWriter().println(JSON.toJSONString(message));
            e.printStackTrace();
        } catch (Exception e) {
            message.put("msg", "网络异常");
            //响应message到前端
            response.getWriter().println(JSON.toJSONString(message));
            e.printStackTrace();
        }
    }
}